package my.jieh.tips.util.prefs;

/**
 * <p>Title: Core Java Technologies Tech Tips</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2002</p>
 * <p>Company: Blueimp</p>
 * @author jieh
 * @version 1.0
 */
import java.awt.event.*;
import java.util.prefs.*;
import javax.swing.*;

/**
 * A frame to test some basic functionality in the Preferences API
 *
 * @author Object Computing Inc.
 */
public class PreferenceTestFrame extends JFrame {

  // A reference to a Preferences object
  private Preferences myPreferences = null;

  // Default values for this frame's preferences
  public static final int DEFAULT_WINDOW_X = 50;
  public static final int DEFAULT_WINDOW_Y = 50;
  public static final int DEFAULT_WINDOW_WIDTH = 300;
  public static final int DEFAULT_WINDOW_HEIGHT = 100;

  // Keys for this frame's preferences
  public static final String WINDOW_X_KEY = "TEST_WINDOW_X";
  public static final String WINDOW_Y_KEY = "TEST_WINDOW_Y";
  public static final String WINDOW_WIDTH_KEY = "TEST_WINDOW_WIDTH";
  public static final String WINDOW_HEIGHT_KEY = "TEST_WINDOW_HEIGHT";

  public PreferenceTestFrame() {
    super("Preferences Test Window");

    // Obtain a references to a Preferences object
    myPreferences = Preferences.userNodeForPackage(this.getClass());

    // Retrieve the location of the frame from the Preferences object
    int windowX = myPreferences.getInt(WINDOW_X_KEY, DEFAULT_WINDOW_X);
    int windowY = myPreferences.getInt(WINDOW_Y_KEY, DEFAULT_WINDOW_Y);

    // Retrieve the size of the frame from the Preferences object
    int windowWidth =
        myPreferences.getInt(WINDOW_WIDTH_KEY, DEFAULT_WINDOW_WIDTH);
    int windowHeight =
        myPreferences.getInt(WINDOW_HEIGHT_KEY, DEFAULT_WINDOW_HEIGHT);

    // Set the size and location of the frame
    setBounds(windowX, windowY, windowWidth, windowHeight);

    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        exitApp();
      }
    });
  }

  private void exitApp() {
    // Save the state of the window as preferences
    myPreferences.putInt(WINDOW_WIDTH_KEY, getWidth());
    myPreferences.putInt(WINDOW_HEIGHT_KEY, getHeight());
    myPreferences.putInt(WINDOW_X_KEY, getX());
    myPreferences.putInt(WINDOW_Y_KEY, getY());
    System.exit(0);
  }

  public static void main(String[] args) {
    new PreferenceTestFrame().show();
  }
}